package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONObject;

import android.R.integer;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.tencent.mm.opensdk.utils.Log;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.activity.NewWordsYuXiActivity.MyReceiver;
import com.ycsj.goldmedalnewconcept.activity.NewWordsYuXiActivity.TimingReceiver;
import com.ycsj.goldmedalnewconcept.adapter.ClassListAdapter;
import com.ycsj.goldmedalnewconcept.bean.AnswerInfo;
import com.ycsj.goldmedalnewconcept.bean.AnswerUpdate;
import com.ycsj.goldmedalnewconcept.bean.TopicInfo;
import com.ycsj.goldmedalnewconcept.bean.timeresq;
import com.ycsj.goldmedalnewconcept.bean.TopicInfo.QuestionListBean;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.fragment.AnswerFragment;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;

/**
 * 答题列表详情的界面
 * 
 * @author Administrator
 *
 */
@SuppressLint({ "NewApi", "InlinedApi" })
public class AnswerListDetailsActivity extends FragmentActivity implements
		View.OnClickListener {

	// 顶部的返回
	private LinearLayout llBack;
	// 顶部的保存
	private TextView tvSave;

	// 列表控件
	private ListView lv;

	// 加载框布局
	private LinearLayout llLoading;

	// 填充列表的数据源
	private List<AnswerInfo> datas;
	private ClassListAdapter adapter;
	private String lessonId;
	private String account;
	private String role;
	private String rid;

	public static final String FINISH = "finish";
	
		
	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_answer_list);

		// 设置状态栏
		setBar();

		// 初始化控件
		initView();

		// 设置监听
		InitListener();

		// 获取数据
		getCachData();
		
		initRegisterBroadCast();

	}

	
	/**
	 * 注册广播
	 */
	private void initRegisterBroadCast() {
		
		
		IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(new TimingReceiver(), filter);
	}

	
	/**
	 * 断网计时广播接受者
	 * 
	 * @author Administrator
	 *
	 */
	class TimingReceiver extends BroadcastReceiver {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			
			 // 监听网络连接，包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
	        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
	            //获取联网状态的NetworkInfo对象
	            NetworkInfo info = intent
	                    .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
	            if (info != null) {
	                //如果当前的网络连接成功并且网络连接可用
	                if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
	                    if (info.getType() == ConnectivityManager.TYPE_WIFI
	                            || info.getType() == ConnectivityManager.TYPE_MOBILE) {
	                    	
	                    	Log.i("test", "网络重新连接");
//	        				UiHelper.toast(context, "网络重新连接");
	                    	
	        				String gradeid = String.valueOf(lessonId).substring(0, 4);
	        				HttpUtils httpUtils2 = new HttpUtils();
	        				httpUtils2.configCurrentHttpCacheExpiry(1000);
	        				httpUtils2.send(HttpMethod.GET,
	        						NetConstant.USERONLINE
	        								+ "InitInterfaceBegin.aspx?msg=1&type=3&account="
	        								+ SPUtils.getString(AnswerListDetailsActivity.this, "account")
	        								+ "&gradeid=" + gradeid + "&lessonid=" + lessonId,
	        						callBackTime);
	                    }
	                }
	            }
	        }
		}
	}
	
	
	/**
	 * 获取页面数据
	 */
	@SuppressWarnings("static-access")
	private void getCachData() {

		datas = new ArrayList<>();
		lessonId = getIntent().getStringExtra("lESSON_ID");
		account = SPUtil.getString(AnswerListDetailsActivity.this,"account","");
		role = SPUtil.getString(AnswerListDetailsActivity.this,"role","");
		
		if(SPUtils.getBoolean(AnswerListDetailsActivity.this,lessonId+"0")){
			//有成绩
			
			OkHttpClient mOkHttpClient = new OkHttpClient();

			String getUrl = Constant.SERVER_tk+":6060/Test_Bank/UnitTest/GetLessonRepeatQuestion.aspx?"
					+ "lessonid="+lessonId+"&account="+account+"&done=1&role="+role;

			Request request = new Request.Builder().url(getUrl).get().build();
			mOkHttpClient.newCall(request).enqueue(new Callback() {

				@Override
				public void onFailure(Request arg0, IOException arg1) {

					// 请求失败
					// 没有数据
					runOnUiThread(new Runnable() {
						public void run() {
							if (null != llLoading) {
								llLoading.setVisibility(View.GONE);
							}
							UiHelper.toast(AnswerListDetailsActivity.this, "网络错误");
							return;
						}
					});

				}

				@SuppressWarnings("static-access")
				@Override
				public void onResponse(Response arg0) throws IOException {
					// 请求成功
					String json = arg0.body().string();
					
					Log.i("test", "json!!!!"+json);
					try {
						if (!TextUtils.isEmpty(json)) {
							TopicInfo info = GsonUtil.jsonToBean(json,
									TopicInfo.class);
							// 取出所有的题目信息
							final List<QuestionListBean> question_list = info
									.getQuestion_list();
							if (question_list == null || question_list.size() == 0) {
								
								
								
								// 证明当前没有题目信息
								runOnUiThread(new Runnable() {
									public void run() {

										if (null != llLoading) {
											llLoading.setVisibility(View.GONE);
										}

										UiHelper.toast(
												AnswerListDetailsActivity.this,
												"该单元无数据");
										return;
									}
								});

							}else{
								
								
								runOnUiThread(new Runnable() {
									public void run() {
										for (int i = 0; i < question_list.size(); i++) {
										
										AnswerInfo answerInfo = new AnswerInfo();
										answerInfo.audioPath = "";
										answerInfo.path = question_list.get(i).getAudio();
										
										
										
										answerInfo.questionContent = question_list.get(i).getDialogue();
										answerInfo.score = Float.parseFloat(question_list.get(i).getQuestion_score());
										answerInfo.isShowScore = true;
										answerInfo.question_id = question_list.get(i).getQuestion_id();
										answerInfo.question_type = question_list.get(i).getQuestion_type();
										datas.add(answerInfo);
									}
									setData();
										return;
									}
								});
								
							}
						} else {
							// 没有数据
							runOnUiThread(new Runnable() {
								public void run() {
//									UiHelper.toast(AnswerListDetailsActivity.this,
//											"该单元无数据");
									if (null != llLoading) {
										llLoading.setVisibility(View.GONE);
									}
									return;
								}
							});
						}

					} catch (Exception e) {
						Log.i("test", e.toString());
					}
				}
			});
			
			
			
			
		}else{
			String answerJson = SPUtil.getString(this, lessonId,"");
			Log.i("test",answerJson);

			if (!TextUtils.isEmpty(answerJson)) {
				datas = GsonUtil.jsonToList(answerJson, AnswerInfo[].class);
				// 设置数据
				setData();
			}
		}
		
		
		
		
		
	}

	/**
	 * 给列表设置数据的方法
	 */
	private void setData() {
		llLoading.setVisibility(View.GONE);
		lv.setVisibility(View.VISIBLE);
		Log.i("test", "datas"+datas.size());
		adapter = new ClassListAdapter(this,this, datas,
				R.layout.item_lv_answer_list);
		lv.setAdapter(adapter);
	}
 
	/**
	 * 初始化View的方法
	 */
	private void initView() {
		llBack = (LinearLayout) findViewById(R.id.ll_back);
		tvSave = (TextView) findViewById(R.id.tv_save);
		lv = (ListView) findViewById(R.id.lv);
		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		lv.setVisibility(View.GONE);
		llLoading.setVisibility(View.VISIBLE);
	}

	/**
	 * 设置监听的方法
	 */
	private void InitListener() {
		llBack.setOnClickListener(this);
		tvSave.setOnClickListener(this);
	}

	/**
	 * 页面控件的点击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_back:
			// 返回
			finish();
			break;
		case R.id.tv_save:
			//游客
			if(account==null||TextUtils.isEmpty(account)){
				
				Intent intent = new Intent(AnswerListDetailsActivity.this,
						LoginActivity.class);
				startActivity(intent);
				finish();
				
			}else{
			
			// 将数据上传给服务器的数据
			UiHelper.showDialog(this, "提交中");
			OkHttpClient mOkHttpClient = new OkHttpClient();
			// 创建上传的数据集合
			List<AnswerUpdate> updatas = new ArrayList<>();

			// 计算总分数
			float score = 0;
			for (int i = 0; i < datas.size(); i++) {
				score += datas.get(i).score;
				AnswerUpdate info = new AnswerUpdate();
				info.question_id = datas.get(i).question_id;
				info.question_type = datas.get(i).question_type;
				info.question_score = datas.get(i).score;
				updatas.add(info);
			}
			
			// 生成上传的Json字符串
			String passJson = GsonUtil.listToJson(updatas);
			
			Log.i("test", "上传的数据是:score" + score + "----passjon的值是:" + passJson);
			
			// 拼接上传字符串
			String baseUrl = Constant.SERVER_tk+":8080/ycsj_platform/ycsj_platform.aspx";
			String getUrl = baseUrl
					+ "?type=7&account="+account+"&role="+role+"&lesson_id="
					+ lessonId + "&total_time=0&score=" + score
					+ "&question_list=" + passJson;

			Request request = new Request.Builder().url(getUrl).get().build();

			mOkHttpClient.newCall(request).enqueue(new Callback() {

				@Override
				public void onFailure(Request arg0, IOException arg1) {
					// 请求失败
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							UiHelper.dismissDialog();
							// 请求失败,主线程更新UI操作
							Toast.makeText(AnswerListDetailsActivity.this,
									"网络错误", Toast.LENGTH_SHORT).show();
						}
					});
				}

				@Override
				public void onResponse(Response response) throws IOException {
					// 获取服务器返回的json数据
					final String json = response.body().string();
					Log.i("test", "返回的json是:" + json);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							try {
								JSONObject jsonObject = new JSONObject(json);
								String state = jsonObject
										.getString("resulttype");
								if ("true".equals(state)) {
									
									//广播
									Intent intent = new Intent(FINISH);
									sendBroadcast(intent);
									
									UiHelper.dismissDialog();
									
									SPUtils.put(AnswerListDetailsActivity.this,datas.get(0).lessionId+"0", true);
									
									Toast.makeText(
											AnswerListDetailsActivity.this,
											"提交成功", Toast.LENGTH_SHORT).show();
									finish();
									
								} else {
									// 上传失败
									UiHelper.dismissDialog();
									Toast.makeText(
											AnswerListDetailsActivity.this,
											"提交失败", Toast.LENGTH_SHORT).show();
								}
							} catch (Exception e) {
								e.printStackTrace();
								UiHelper.dismissDialog();
								Log.i("test", e.toString());
							}
						}
					});
				}
			});
			}
			break;
		default:
			break;
		}
	}

	
	
	@Override
	protected void onResume() {
		super.onResume();

		String gradeid = String.valueOf(lessonId).substring(0, 4);
		HttpUtils httpUtils2 = new HttpUtils();
		httpUtils2.configCurrentHttpCacheExpiry(1000);
		httpUtils2.send(HttpMethod.GET,
				NetConstant.USERONLINE
						+ "InitInterfaceBegin.aspx?msg=1&type=9&account="
						+ SPUtils.getString(this, "account")
						+ "&gradeid=" + gradeid + "&lessonid=" + lessonId,
				callBackTime);

	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		if(adapter!=null){
			adapter.stopPlayer();
		}
		
		String gradeid = String.valueOf(lessonId).substring(0, 4);
		HttpUtils httpUtils2 = new HttpUtils();
		httpUtils2.configCurrentHttpCacheExpiry(1000);
		httpUtils2.send(HttpMethod.GET, NetConstant.USERONLINE
				+ "SaveInterfaceEnd.aspx?msg=1&rid=" + rid + "&account="
				+ SPUtils.getString(this, "account"),
				callBackTimefinish);
	}
	

	
	
	
	private RequestCallBack<String> callBackTime = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象
			Gson gson = new Gson();
			timeresq fromJson = gson.fromJson(json, timeresq.class);
			rid = fromJson.rid;
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			rid = "";
			
		}
	};
	
	private RequestCallBack<String> callBackTimefinish = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;
		}

		@Override
		public void onFailure(HttpException error, String msg) {

		}
	};
	
	
	
	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

}
